import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: Administrator
 * \* Date: 2022/3/16
 * \* Time: 14:25
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class TestJDBCUpdate {
    public static void main(String[] args) throws SQLException {
        //根据id来修改学生姓名，让用户输入要修改的id，已经对应的修改后的名字

        //1.创建数据库
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java102?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");

        //2.连接数据库
        Connection connection = dataSource.getConnection();

        //3.输入信息
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要修改的学生id：");
        int id = scanner.nextInt();
        System.out.println("请输入要修改的学生姓名");
        String name = scanner.next();

        //4.拼装update
        String sql = "update student set name = ? where id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,name);
        statement.setInt(2,id);
        System.out.println("statement:" +statement);

        //5.执行sql
        int ret = statement.executeUpdate();
        System.out.println("ret =" + ret);

        //6.回收资源
        statement.close();
        connection.close();
    }
}
